package one.stand.controller.supplier;

import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.*;
import com.jmp.api.util.LabelUtil;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.CardFeign;
import com.jmp.feign.CompanyFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.*;
import one.stand.enums.LoginEnum;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiCrmAppMapper;
import one.stand.mapper.IndustryMapperExt;
import one.stand.mapper.WebsiteMapperExt;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "店铺页-创建店铺|工作台|编辑名片|我的产品|企业编辑")
@RequestMapping("supplier/my")
@RestController
public class SupplierMyController {
    @Autowired
    private CompanyFeign companyFeign;
    @Autowired
    private CardFeign cardFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private WebsiteMapperExt websiteMapperExt;
    @Autowired
    private IndustryMapperExt industryMapperExt;

    @Autowired
    private GoodsApiCrmAppMapper goodsApiCrmAppMapper;

    @ApiOperation("1店铺信息")
    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<SupplierMyInfoResponse> info(@RequestAttribute SupplierMyInfoRequest request) {

        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        int status;
        String refuseReason = StringUtils.EMPTY;
        if (Objects.isNull(optUser.getCompanyId())) {
            status = 0;

            //名片审核
            BusinessCard card = businessCardBaseService.getByUserId(optUser.getUserId());
            if (Objects.nonNull(card) && card.getIsDel() == 0 && card.getAuditState() == 0) {
                status = 1;
            }
        } else {
            //店铺审核
            CompanyLicenseInfoRequest licenseInfoRequest = CompanyLicenseInfoRequest.builder().companyId(optUser.getCompanyId()).build();
            ResultModel<CompanyLicenseInfoResponse> licenseInfoResponseResultModel = companyFeign.licenseInfo(licenseInfoRequest);
            AssertUtil.isTrue(licenseInfoResponseResultModel);
            CompanyLicenseInfoResponse licenseInfoResponse = licenseInfoResponseResultModel.getData();
            if (Objects.isNull(licenseInfoResponse.getStatus())) {
                status = 2;
            } else {
                status = licenseInfoResponse.getStatus() + 1;
                refuseReason = licenseInfoResponse.getRefuseReason();
            }
        }

        SupplierMyInfoResponse.SupplierMyInfoResponseBuilder response = SupplierMyInfoResponse.builder()
                .status(status)
                .refuseReason(refuseReason);

        if (status == 2 && Objects.nonNull(optUser.getCardId())) {//存在名片时,获取名片信息


            CompanyServiceDto companyServiceDto = companyBaseService.getService(optUser.getCompanyId());
            response.cardNumTotal(companyServiceDto.getCurrentNum())
                    .cardNumUnused(companyServiceDto.getAvailableNum());

            //名片
            BusinessCard card = businessCardBaseService.getCustomer(optUser.getCardId());
            Company2Dto company = companyBaseService.get2(optUser.getCompanyId());
            Double rateRank = businessCardBaseService.getRateRank(optUser.getCardId());
            response.companyName(company.getCompanyName())
                    .cardName(card.getName())
                    .logo(card.getLogo())
                    .position(card.getPosition())
                    .phone(card.getPhone())
                    .email(card.getEmail())
                    .perfectRate(card.getPerfectRate())
                    .perfectRateRank(rateRank)
                    .style(card.getStyle());

            //名片分享
            TemplateGet2Request createRequest = TemplateGet2Request.builder()
                    .templateType(TemplateApi.Type.ID_CRM_APP_CARD)
                    .cardId(optUser.getCardId())
                    .build();
            ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(createRequest);
            AssertUtil.isTrue(getResponseResultModel);
            String cardUrl = getResponseResultModel.getData().getImageUrl();
            createRequest = TemplateGet2Request.builder()
                    .templateType(TemplateApi.Type.ID_WECHAT_CARD)
                    .cardId(optUser.getCardId())
                    .build();
            getResponseResultModel = templateFeign.get2(createRequest);
            AssertUtil.isTrue(getResponseResultModel);
            String wechatImgUrl = getResponseResultModel.getData().getImageUrl();
            AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                    .companyId(optUser.getCompanyId())
                    .loginEnum(LoginEnum.USER)
                    .build();
            ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
            String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;
            response.wechatId(wechatId)
                    .path("/pages/index/main?companyId=" + card.getCompanyId() + "&cardId=" + card.getCardId() + "&goType=1")
                    .wechatImgUrl(wechatImgUrl)
                    .cardUrl(cardUrl);
        }

        return ResultModel.success(response.build());
    }

    @ApiOperation("2创建：已注册店铺列表（可搜索，分页）")
    @GetMapping("company/select")
    @SecurityAuthCheck
    public ResultModel<SupplierMyCompanySelectResponse> companySelect(@RequestAttribute SupplierMyCompanySelectRequest request) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyDto> list = companyBaseService.selectList(request.getKeyword(), null);
        PageResponse2<SupplierMyCompanySelectResponse.Company> page = ConvertUtils.page2(list, companyDto -> {
            return SupplierMyCompanySelectResponse.Company.builder()
                    .companyId(companyDto.getCompanyId())
                    .companyName(companyDto.getCompanyName())
                    .build();
        });

        SupplierMyCompanySelectResponse response = SupplierMyCompanySelectResponse.builder()
                .companyPage(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("2创建：保存")
    @PostMapping("save")
    @SecurityAuthCheck
    public ResultModel save(@RequestAttribute SupplierMySaveRequest request) {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();

        boolean isClientJxs = Objects.nonNull(request.getCompanyType()) && BooleanUtils.toBoolean(request.getCompanyType());

        CardSaveRequest cardSaveRequest = CardSaveRequest.builder()
                .companyLogo(request.getCompanyLogo())
                .companyName(request.getCompanyName())
                .licensePhotos(request.getLicensePhotos())
                .password(String.valueOf(RandomUtil.randomInt(100000, 999999)))
//                .companyNotice(request.getCompanyNotice())
                .industryId(industryMapperExt.selectByName("经销商"))
                .companyId(request.getCompanyId())
                .isClientJxs(isClientJxs)
                .noPassword(true)

                .logo(request.getLogo())
                .name(request.getName())
                .phone(request.getPhone())
                .personalWx(request.getPersonalWx())
                .email(request.getEmail())
                .style(1)
//                .companyWx(request.getCompanyWx())
//                .photo(request.getPhoto())
//                .position(request.getPosition())
//                .soundRecording(request.getSoundRecording())
//                .soundTime(request.getSoundTime())
//                .briefIntroduction(request.getBriefIntroduction())

                .id(requestContext.getUser().getUserId())
                .companyKey(requestContext.getRequest().getCompanyKey())
                .token(requestContext.getRequest().getToken())
                .build();
        ResultModel resultModel = cardFeign.save(cardSaveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "3编辑名片-详情")
    @GetMapping("card")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<SupplierMyCardResponse> card() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        BusinessCard card = businessCardBaseService.getCustomer(optUser.getCardId());

        SupplierMyCardResponse response = SupplierMyCardResponse.builder()
                .logo(card.getLogo())
                .name(card.getName())
                .phone(card.getPhone())
                .position(card.getPosition())
                .personalWx(card.getPersonalWx())
                .wxCode(card.getWxCode())
                .email(card.getEmail())
                .soundTime(card.getSoundTime())
                .soundRecording(card.getSoundRecording())
                .photos(card.getPhoto())
                .briefIntroduction(card.getBriefIntroduction())
                .style(card.getStyle())
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3编辑名片-保存")
    @PostMapping("card/save")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel cardSave(@RequestAttribute SupplierMyCardSaveRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        CardEditDto editDto = CardEditDto.builder()
                .cardId(optUser.getCardId())
                .logo(request.getLogo())
                .name(request.getName())
                .phone(request.getPhone())
                .position(request.getPosition())
                .personalWx(request.getPersonalWx())
                .wxCode(request.getWxCode())
                .email(request.getEmail())
                .soundTime(request.getSoundTime())
                .soundRecording(request.getSoundRecording())
                .photos(request.getPhotos())
                .briefIntroduction(request.getBriefIntroduction())
                .style(request.getStyle())
                .build();
        ResultModel resultModel = cardFeign.edit(editDto);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "4我的产品: 分类")
    @GetMapping("goods/type")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<SupplierMyGoodsTypeResponse> goodsType() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        //商品分类
        List<GoodsType> goodstypeModelList = goodsApiCrmAppMapper.selectTypes(optUser.getCompanyId());
        List<SupplierMyGoodsTypeResponse.Type> types = OneListUtil.group(goodstypeModelList,
                goodsType -> goodsType.getParentId() == 0,
                GoodsType::getGoodstypeId,
                GoodsType::getParentId,
                (parent, child) -> parent.getChildList().add(child),
                goodsType -> SupplierMyGoodsTypeResponse.Type.builder()
                        .typeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .childList(Lists.newLinkedList())
                        .build(),
                goodsType -> SupplierMyGoodsTypeResponse.Type.builder()
                        .typeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .groupName(goodsType.getGroupName())
                        .build());

        SupplierMyGoodsTypeResponse response = SupplierMyGoodsTypeResponse.builder()
                .types(types)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "4我的产品: 产品列表（分页|模糊搜索）")
    @GetMapping("goods")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<SupplierMyGoodsResponse> goods(@RequestAttribute SupplierMyGoodsRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        String goodsNameLike = SqlUtil.like(request.getKeyword());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> list = goodsApiCrmAppMapper.selectSupplierGoods(request.getTypeId(), optUser.getCompanyId(), goodsNameLike);
        PageResponse2<SupplierMyGoodsResponse.Goods> goodsPage = ConvertUtils.page2(list, goodsModel -> {
            boolean hasVr = StringUtils.isNoneBlank(goodsModel.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goodsModel.getGoodsId());
            boolean hasVideo = StringUtils.isNoneBlank(goodsModel.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goodsModel.getCompanyId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goodsModel.getGoodsId());

            return SupplierMyGoodsResponse.Goods.builder()
                    .goodsId(goodsModel.getGoodsId())
                    .goodsName(goodsModel.getGoodsName())
                    .photo(OneStringUtils.photoResize(goodsPhotoService.getPath(goodsModel.getGoodsId())))
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .popularityNum(popularityNum)
                    .build();
        });
        SupplierMyGoodsResponse response = SupplierMyGoodsResponse.builder()
                .goodsList(goodsPage)
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation(value = "5企业信息")
    @GetMapping("company")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<SupplierMyCompanyResponse> company() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        Company2Dto company = companyBaseService.get2(optUser.getCompanyId());
        AssertUtil.nonNull(company, ResultEnum.NO_DATA);
        AssertUtil.isTrue(company.countOn(), ResultEnum.NO_DATA);

        Website website = websiteMapperExt.selectByCompanyId(optUser.getCompanyId());

        ResultModel<CompanyLicenseInfoResponse> licenseInfoResponseResultModel = companyFeign.licenseInfo(CompanyLicenseInfoRequest.builder().companyId(optUser.getCompanyId()).build());
        AssertUtil.isTrue(licenseInfoResponseResultModel);

        SupplierMyCompanyResponse response = SupplierMyCompanyResponse.builder()
                .companyName(company.getCompanyName())
                .companyLogo(company.getCompanyLogo())
                .licensePhotos(licenseInfoResponseResultModel.getData().getPhotos())
                .address(website.getAddress())
                .latitude(website.getLatitude())
                .longitude(website.getLongitude())
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "5企业信息:地市列表")
    @GetMapping("company/city")
    public ResultModel<SupplierMyCompanyCityResponse> companyCity() {

        List<String> cityList = goodsApiCrmAppMapper.selectCity();

        SupplierMyCompanyCityResponse response = SupplierMyCompanyCityResponse.builder()
                .cityList(cityList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "5企业信息-保存")
    @PostMapping("company/save")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel companySave(@RequestAttribute SupplierMyCompanySaveRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        CompanyEditRequest companyEditRequest = CompanyEditRequest.builder()
                .companyId(optUser.getCompanyId())
                .companyLogo(request.getCompanyLogo())
                .companyName(request.getCompanyName())
                .licensePhotos(request.getLicensePhotos())
                .address(request.getAddress())
                .latitude(request.getLatitude())
                .longitude(request.getLongitude())
                .build();
        ResultModel resultModel = companyFeign.edit(companyEditRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
